﻿Imports System
Imports System.Collections.Generic
Imports System.IO
Imports System.Net
Imports System.Text
Imports System.Xml
Imports Newtonsoft.Json
Imports System.Runtime.Serialization
Class Tuple(Of T1, T2, T3)
    Public Property Item1() As T1

    Public Property Item2() As T2

    Public Property Item3() As T3

    Public Sub New(tt1 As T1, tt2 As T2, tt3 As T3)
        Me.Item1 = tt1
        Me.Item2 = tt2
        Me.Item3 = tt3
    End Sub
End Class

Class Util
    Public Shared Function HttpPost(action As String, data As Byte()) As Stream
        Dim myRequest As HttpWebRequest = TryCast(WebRequest.Create(action), HttpWebRequest)
        myRequest.Method = "POST"
        myRequest.Timeout = 20000
        myRequest.ContentType = "application/x-www-form-urlencoded"
        myRequest.ContentLength = CLng(data.Length)
        Using newStream As Stream = myRequest.GetRequestStream()
            newStream.Write(data, 0, data.Length)
        End Using
        Dim myResponse As HttpWebResponse = TryCast(myRequest.GetResponse(), HttpWebResponse)
        Return myResponse.GetResponseStream()
    End Function

    Public Shared Function HttpPost2(action As String, data As String) As String
        Dim buffer As Byte() = Encoding.UTF8.GetBytes(data)
        Dim result As String
        Using stream As Stream = Util.HttpPost(action, buffer)
            Dim sr As StreamReader = New StreamReader(stream)
            data = sr.ReadToEnd()
            result = data
        End Using
        Return result
    End Function

    Public Shared Function HttpPost2(action As String, data As Byte()) As String
        Dim result As String
        Using stream As Stream = Util.HttpPost(action, data)
            Dim sr As StreamReader = New StreamReader(stream)
            result = sr.ReadToEnd()
        End Using
        Return result
    End Function

    Public Shared Function HttpUpload(action As String, file As String) As String
        Dim boundary As String = "---------------------------" + DateTime.Now.Ticks.ToString("x")
        Dim myRequest As HttpWebRequest = TryCast(WebRequest.Create(action), HttpWebRequest)
        myRequest.Method = "POST"
        myRequest.ContentType = "multipart/form-data;boundary=" + boundary
        Dim sb As StringBuilder = New StringBuilder()
        sb.Append("--" + boundary)
        sb.Append(vbCrLf)
        sb.Append("Content-Disposition: form-data; name=""media""; filename=""" + file + """")
        sb.Append(vbCrLf)
        sb.Append("Content-Type: application/octet-stream")
        sb.Append(vbCrLf & vbCrLf)
        Dim head As String = sb.ToString()
        Dim form_data As Byte() = Encoding.UTF8.GetBytes(head)
        Dim foot_data As Byte() = Encoding.UTF8.GetBytes(vbCrLf & "--" + boundary + "--" & vbCrLf)
        Dim length As Long = CLng((form_data.Length + foot_data.Length))
        Using fileStream As FileStream = New FileStream(file, FileMode.Open, FileAccess.Read)
            length += fileStream.Length
            myRequest.ContentLength = length
            Dim requestStream As Stream = myRequest.GetRequestStream()
            requestStream.Write(form_data, 0, form_data.Length)
            Dim buffer(CUInt(Math.Min(4095, CInt(fileStream.Length) - 1))) As Byte
            Dim bytesRead As Integer
            While (bytesRead = fileStream.Read(buffer, 0, buffer.Length)) <> 0
                requestStream.Write(buffer, 0, bytesRead)
            End While
            requestStream.Write(foot_data, 0, foot_data.Length)
        End Using
        Dim myResponse As HttpWebResponse = TryCast(myRequest.GetResponse(), HttpWebResponse)
        Dim sr As StreamReader = New StreamReader(myResponse.GetResponseStream(), Encoding.UTF8)
        Dim json As String = sr.ReadToEnd().Trim()
        sr.Close()
        If myResponse IsNot Nothing Then
            myResponse.Close()
            myRequest = Nothing
        End If
        If myRequest IsNot Nothing Then
            myRequest = Nothing
        End If
        Return json
    End Function

    Public Shared Function HttpGet(action As String) As Tuple(Of Stream, String, String)
        Dim myRequest As HttpWebRequest = TryCast(WebRequest.Create(action), HttpWebRequest)
        myRequest.Method = "GET"
        myRequest.Timeout = 20000
        Dim myResponse As HttpWebResponse = TryCast(myRequest.GetResponse(), HttpWebResponse)
        Dim stream As Stream = myResponse.GetResponseStream()
        Dim ct As String = myResponse.ContentType
        Dim result As Tuple(Of Stream, String, String)
        If ct.IndexOf("json") >= 0 OrElse ct.IndexOf("text") >= 0 Then
            Using sr As StreamReader = New StreamReader(stream)
                Dim json As String = sr.ReadToEnd()
                result = New Tuple(Of Stream, String, String)(Nothing, ct, json)
                Return result
            End Using
        End If
        Dim MyStream As Stream = New MemoryStream()
        Dim buffer(4095) As Byte
        Dim bytesRead As Integer
        While (bytesRead = stream.Read(buffer, 0, buffer.Length)) <> 0
            MyStream.Write(buffer, 0, bytesRead)
        End While
        MyStream.Position = 0L
        result = New Tuple(Of Stream, String, String)(MyStream, ct, String.Empty)
        Return result
    End Function

    Public Shared Function HttpGet2(action As String) As String
        Return Util.HttpGet(action).Item3
    End Function

    Public Shared Function ToJson(obj As Object) As String
        Return JsonConvert.SerializeObject(obj)
    End Function

    Public Shared Function JsonTo(Of T)(json As String) As T
        Return JsonConvert.DeserializeObject(Of T)(json)
    End Function

    Public Shared Function GetDictFromXml(xml As String) As Dictionary(Of String, String)
        Dim doc As XmlDocument = New XmlDocument()
        doc.LoadXml(xml)
        Dim dict As Dictionary(Of String, String) = New Dictionary(Of String, String)()
        For Each node As XmlNode In doc.DocumentElement.ChildNodes
            dict.Add(node.Name, node.InnerText.Trim())
        Next
        Return dict
    End Function
End Class
